/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-07-17     Administrator       the first version
 */

#include <stdint.h>
#include <stdio.h>
#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include "dhtxx.h"
#include "bsp_api.h"
#define DATA_PIN                 BSP_IO_PORT_01_PIN_02
struct rt_sensor_data temp_data,humi_data;
static rt_device_t humi_dev = RT_NULL;
static rt_device_t temp_dev = RT_NULL;
static void dht11_entry(void* params)
{
    while(1)
    {
        if (1 != rt_device_read(humi_dev, 0, &humi_data, 1))
        {
            rt_kprintf("Read humi data failed.\n");
        }
        else
        {
            //rt_kprintf("[%d] Humi: %d\n", humi_data.timestamp, humi_data.data.humi);
        }
        if (1 != rt_device_read(temp_dev, 0, &temp_data, 1))
        {
            rt_kprintf("Read temp data failed.\n");
        }
        else
        {
            //rt_kprintf("[%d] Temp: %d\n", temp_data.timestamp, temp_data.data.temp);
        }


        rt_thread_mdelay(3000);
    }

}
static int dht11_thread(void)
{


    humi_dev = rt_device_find("humi_dht");
    if(!humi_dev)
    {
        rt_kprintf("can not find humi device\n");
        return -1;
    }

    if (rt_device_open(humi_dev, RT_DEVICE_FLAG_RDWR))
    {
        rt_kprintf("Open humi device failed.\n");
        return -1;
    }


    temp_dev  = rt_device_find("temp_dht");
    if (!temp_dev)
    {
        rt_kprintf("Can't find temp device.\n");
        return -1 ;
    }

    if (rt_device_open(temp_dev, RT_DEVICE_FLAG_RDWR))
    {
        rt_kprintf("Open temp device failed.\n");
        return -1;
    }

    rt_thread_t dht11_thread;
    dht11_thread = rt_thread_create("dht11_thread", dht11_entry, RT_NULL, 1024, 14, 20);
    if(dht11_thread)
    {
        rt_thread_startup(dht11_thread);
    }
}
INIT_APP_EXPORT(dht11_thread);
